package com.zzyl.nursing.service.impl;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.mapper.MemberReservationMapper;
import com.zzyl.nursing.service.IMemberReservationService;
import com.zzyl.nursing.vo.ReservationCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class MemberReservationServiceImpl extends ServiceImpl<MemberReservationMapper, Reservation> implements IMemberReservationService {
    @Autowired
    private FamilyMemberServiceImpl familyMemberService;

    @Autowired
    MemberReservationMapper memberReservationMapper;

    /**
     * 获取已取消预约数量
     *
     * @return
     */
    @Override
    public Long cancelledCount() {
        // 获取当前线程本地用户ID
        Long userId = UserThreadLocal.getUserId();
        // 检查用户是否已登录
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        // 根据用户ID查询家庭成员信息
        LambdaQueryWrapper<FamilyMember> eqed = Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getId, userId);
        FamilyMember familyMember = familyMemberService.getOne(eqed);
        // 检查家庭成员信息是否存在
        if (ObjectUtils.isEmpty(familyMember)) {
            throw new RuntimeException("没有找到该用户id为:" + userId);
        }
        // 获取家庭成员姓名
        String phone = familyMember.getPhone();
        // 获取当前时间戳
        long time = System.currentTimeMillis();
        // 将时间戳转换为LocalDateTime对象
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        // 获取当天开始时间
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        // 获取当天结束时间
        LocalDateTime endTime = startTime.plusDays(1);
        // 查询预约记录，条件为姓名匹配且时间在当天范围内
        LambdaQueryWrapper<Reservation> wrapper = Wrappers.<Reservation>lambdaQuery().eq(Reservation::getMobile, phone)
                .between(Reservation::getCreateTime, startTime, endTime)
                .eq(Reservation::getStatus, 2);
        // 返回符合条件的预约记录数
        return baseMapper.selectCount(wrapper);
    }

    /**
     * 根据时间戳查询当天预约数量
     *
     * @param time
     * @return
     */
    @Override
    public List<ReservationCountVo> countByTime(Long time) {
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = localDateTime.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        List<ReservationCountVo> list = memberReservationMapper.countByTime(startTime, endTime);

        return list;


    }


    /**
     * 添加预约信息
     * <p>
     * 该方法负责将传入的预约信息（ReservationDto对象）转换为预约实体（Reservation），并保存到数据库中
     * 主要涉及日期时间的解析、预约实体的构建以及数据的保存操作
     *
     * @param dto 包含预约信息的数据传输对象
     */
    @Override
    public void add(ReservationDto dto) {
        Long count = cancelledCount();
        if (count > 3) {
            throw new RuntimeException("今日取消预约三次，无法再预约，请明日再试");
        }
        // 创建日期时间格式化器，用于解析字符串日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析预约时间字符串，转换为LocalDateTime类型
        LocalDateTime dateTime = LocalDateTime.parse(dto.getTime(), formatter);
        // 使用Builder模式构建Reservation实体对象
        Reservation build = Reservation.builder()
                .mobile(dto.getMobile()) // 设置手机号
                .name(dto.getName()) // 设置姓名
                .type(dto.getType()) // 设置预约类型
                .visitor(dto.getVisitor()) // 设置访问者人数
                .time(dateTime) // 设置预约时间
                .status(0) // 初始化预约状态为0，表示未处理
                .createTime(LocalDateTime.now()) // 设置创建时间为当前时间
                .build(); // 完成构建
        LambdaQueryWrapper<Reservation> wrapper = Wrappers.<Reservation>lambdaQuery()
                .eq(Reservation::getMobile, dto.getMobile())
                .eq(Reservation::getStatus, 0);
        Reservation one = getOne(wrapper);
        if (ObjectUtils.isNotEmpty(one)) {
            throw new RuntimeException("该手机号已预约");
        }
        // 保存构建好的预约实体到数据库
        save(build);
    }

    @Override
    public List<Reservation> pageSize(ReservationDto dto) {
        IPage<Reservation> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Reservation> wrapper = Wrappers.<Reservation>lambdaQuery()
                .eq(dto.getStatus() != null, Reservation::getStatus, dto.getStatus())
                .select(Reservation::getId);
        IPage<Reservation> reservationIPage = page(page, wrapper);
        return reservationIPage.getRecords();
    }

    @Override
    public void cancel(Long id) {
        Reservation reservation = new Reservation();
        reservation.setStatus(2);
        LambdaQueryWrapper<Reservation> wrapper = Wrappers.<Reservation>lambdaQuery().eq(Reservation::getId, id);
        memberReservationMapper.update(reservation, wrapper);
    }


}
